﻿using EnterpriseInformation.Common;
using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EnterpriseInformation.DataModel
{
    public class RiskInformation: CustomLog
    {

        RegexClass regexClass;

        public RiskInformation(string companyName, string unique, string userName) 
        {
            InitLog(userName);
            this.UserName = userName;
            this.CompanyName = companyName;
            this.Unique = unique;
            regexClass = new RegexClass();
        }
         
        public void Init(string htmlContent)
        {

            try
            {

                doc = new HtmlDocument();
                doc.LoadHtml(htmlContent);
 

            }
            catch (Exception ex)
            {
                MyLog().Error("风险信息初始化:" + ex.ToString());
            }

        }


        public string CompanyName
        {
            get;
            set;
        }

        public string Unique { get; set; }


        public HtmlDocument doc; 
         

        /// <summary>
        /// 解析下一页文书列表
        /// </summary>
        /// <param name="htmlContent"></param>
        /// <returns></returns>
        public JObject ParseJudgementListPage(string htmlContent) 
        {
            try
            { 

                HtmlDocument docPag = new HtmlDocument();

                docPag.LoadHtml(htmlContent);

                return ParseJudgement(docPag.DocumentNode);
                 

            }
            catch (Exception ex)
            {

                MyLog().Error("解析下一页文书列表:" + ex.ToString());
            }

            return new JObject();
        }

        /// <summary>
        /// 裁判文书解析
        /// </summary>
        /// <param name="nodeElement"></param>
        /// <returns></returns>
        public JObject ParseJudgement(HtmlNode nodeElement) 
        { 
            try
            {

                JObject judgementList = new JObject();

               //当前页
               string current_page = nodeElement.SelectNodes("./nav/ul/li[@class=\"active\"]/a/text()")[0].InnerText;


                //获取总页数
                HtmlNodeCollection navLis = nodeElement.SelectNodes("./nav/ul/li");

                int total = 1;

                foreach (HtmlNode navLi in navLis)
                {
                   string page_index = navLi.InnerText;

                   page_index = regexClass.RegexString(page_index, "(?<g1>[\\d]+)", "g1"); 

                    if (!string.IsNullOrEmpty(page_index))
                    { 
                        if (total < int.Parse(page_index))
                        {
                            total = int.Parse(page_index);
                        }

                    } 
                } 

                //获取文书
                HtmlNodeCollection judgementDivLists = nodeElement.SelectNodes("./section/div"); 

                JArray judgement = new JArray();

                foreach (HtmlNode judgementDiv in judgementDivLists)
                {

                    //HtmlNodeCollection detailElement =
                    //    judgementDiv.SelectNodes("./a[contains(@class,\"text-primary\") and contains(@class,\"pull-right\")]");


                    //HtmlAttribute  linkElement =  detailElement[0].Attributes["onclick"];

                    //string linkScript = linkElement.Value;

                    //List<string>  riskArgs =  regexClass.RegexListStr(linkScript, "'(?<g1>.*?)'","g1");

                    //JObject riskWenshu = new JObject();

                    //riskWenshu.Add(new JProperty("keyno", riskArgs[0]));

                    //riskWenshu.Add(new JProperty("name", riskArgs[1]));

                    //riskWenshu.Add(new JProperty("tag", riskArgs[2]));

                    //riskWenshu.Add(new JProperty("CaseReason", riskArgs[3]));

                    //riskWenshu.Add(new JProperty("CaseRole", riskArgs[4]));

                    //riskWenshu.Add(new JProperty("p", 1));

                    //JObject query = new JObject(); 
                    //query.Add(new JProperty("url", "/risk_getinfos"));
                    //query.Add(new JProperty("param", riskWenshu));


                    //删除查看详情
                   // detailElement[0].Remove();

                    //标题
                    string risk_title= judgementDiv.InnerText.Replace(" ", "").Trim().Replace("\n查看详情", "");

                    //总数
                    string totalCount = judgementDiv.SelectNodes("./span[@class=\"text-danger\"]")[0].InnerText;


                    JObject jobj = new JObject();

                    jobj.Add(new JProperty("title", risk_title));

                    jobj.Add(new JProperty("total", int.Parse(totalCount)));

                    //jobj.Add(new JProperty("query", query));
                    jobj.Add(new JProperty("query", DetailAction(judgementDiv)));

                    judgement.Add(jobj); 
                } 

                judgementList.Add(new JProperty("current", current_page));
                judgementList.Add(new JProperty("total", total));
                JArray indexArray = new JArray();
                indexArray.Add(judgement); 
                judgementList.Add(new JProperty("data", indexArray));

                if (int.Parse(current_page) < total)
                {
                    string url = $"/risk_getSelfJudgementForCompany?type=judgement&unique={Unique}&p=" + (int.Parse(current_page) + 1).ToString();
                    judgementList.Add(new JProperty("url", url)); 
                }
                 
                return judgementList;

            }
            catch (Exception ex)
            {

                MyLog().Error("裁判文书解析:" + ex.ToString());
            }

            return new JObject();
        
        }

   
        public JObject JudgementList 
        {
            set {; }
            get {

                try
                {
                      
                    HtmlNodeCollection judgement_list = doc.DocumentNode.SelectNodes("//div[@id=\"judgementList\"]");

                    JObject judgementList = ParseJudgement(judgement_list[0]);

                    return judgementList;

                }
                catch (Exception ex)
                {

                    MyLog().Error("裁判文书:" + ex.ToString());
                }

                return new JObject();
            
            }
        }


        /// <summary>
        /// 解析详情链接
        /// </summary>
        /// <param name="judgementDiv"></param>
        /// <returns></returns>
        public JObject DetailAction(HtmlNode judgementDiv) 
        {

            try
            {
                HtmlNodeCollection detailElement =
              judgementDiv.SelectNodes("./a[contains(@class,\"text-primary\") and contains(@class,\"pull-right\")]");


                HtmlAttribute linkElement = detailElement[0].Attributes["onclick"];

                string linkScript = linkElement.Value;

                List<string> riskArgs = regexClass.RegexListStr(linkScript, "'(?<g1>.*?)'", "g1");

                JObject riskDetail = new JObject();

                riskDetail.Add(new JProperty("keyno", riskArgs[0]));

                riskDetail.Add(new JProperty("name", riskArgs[1]));

                riskDetail.Add(new JProperty("tag", riskArgs[2]));

                if (riskArgs.Count > 3)
                {
                    riskDetail.Add(new JProperty("CaseReason", riskArgs[3]));

                }
                 
                if (riskArgs.Count > 4)
                {
                    riskDetail.Add(new JProperty("CaseRole", riskArgs[4]));
                }

                riskDetail.Add(new JProperty("p", 1));

                JObject query = new JObject();

                query.Add(new JProperty("url", "/risk_getinfos"));

                query.Add(new JProperty("param", riskDetail));

                return query;

            }
            catch (Exception ex)
            {

                MyLog().Error("详情链接解析:" + ex.ToString());
            }

            return new JObject();          

        }


        /// <summary>
        /// 其它信息解析
        /// </summary>
        /// <param name="nodeElement"></param>
        /// <returns></returns>
        public JObject ParseOtherInformation(HtmlNode nodeElement)
        {
            try
            {

                JObject otherInfoList = new JObject(); 
                 
                HtmlNodeCollection otherDivLists = nodeElement.SelectNodes("./div");

                JArray judgement = new JArray();

                foreach (HtmlNode otherDiv in otherDivLists)
                { 
                    //标题
                    string risk_title = otherDiv.InnerText.Replace(" ", "").Trim().Replace("\n查看详情", "");
                     

                    HtmlNodeCollection textDanger = otherDiv.SelectNodes("./span[@class=\"text-danger\"]");

                    //总数
                    string totalCount = textDanger[textDanger.Count - 1].InnerText;


                    JObject jobj = new JObject();

                    jobj.Add(new JProperty("title", risk_title));

                    jobj.Add(new JProperty("total", int.Parse(totalCount)));

                    jobj.Add(new JProperty("query", DetailAction(otherDiv))); 

                    judgement.Add(jobj);
                }

               
                JArray indexArray = new JArray();
                indexArray.Add(judgement);
                otherInfoList.Add(new JProperty("data", indexArray)); 

                return otherInfoList;

            }
            catch (Exception ex)
            {

                MyLog().Error("其它信息解析:" + ex.ToString());
            }

            return new JObject();

        }



        public JObject ParseRiskInformation() 
        {

            try
            {

                JObject riskInformation = new JObject();

                Dictionary<string, string> commentList = new Dictionary<string, string>();
                commentList.Add("裁判文书", "judgement_list");
                commentList.Add("立案信息", "lian_list");
                commentList.Add("开庭公告", "notice_list");
                commentList.Add("法院公告", "gonggao");
                commentList.Add("送达公告", "dnotice_list");
                commentList.Add("行政处罚", "allinoneap_list");
                commentList.Add("违规处理", "wg");
                commentList.Add("股权质押", "spledge");
                commentList.Add("对外担保", "dw");


                 


                HtmlNodeCollection panelBodys = doc.DocumentNode.SelectNodes("//section[@class=\"npanel\"]/div[contains(@class,\"npanel-heading\")]/div[contains(@class,\"tab\")]/a"); 

                Dictionary<string, int> moduleDictionary = new Dictionary<string, int>(); 

                foreach (HtmlNode panelBody in panelBodys)
                {
                    try
                    {
                        string moduleNameValue = panelBody.InnerText.Replace(" ", "").Replace("\n", "").Trim();

                        if (string.IsNullOrEmpty(moduleNameValue))
                        {
                            continue;
                        }

                        string keyName = regexClass.RegexString(moduleNameValue, "(?<g1>[\u4e00-\u9fa5]+)", "g1");

                        int keyValue = -1;

                        string kv = regexClass.RegexString(moduleNameValue, "(?<g1>[\\d]+)", "g1");

                        if (!string.IsNullOrEmpty(kv))
                        {
                            keyValue = int.Parse(kv);
                        }

                        if (!moduleDictionary.ContainsKey(keyName))
                        {
                            moduleDictionary.Add(keyName, keyValue);

                        }
                        else

                            moduleDictionary[keyName] = keyValue;

                    }
                    catch (Exception ex)
                    {
                        MyLog().Error("信息打包:" + ex.ToString());

                    }

                }


                if (string.IsNullOrEmpty(this.CompanyName))
                {
                    //重新获取

                    HtmlNodeCollection companyName =
                     doc.DocumentNode.SelectNodes("//div[@class=\"content\"]/div[@class=\"title\"]/node()");

                    this.CompanyName = companyName[0].InnerText.Replace("\n", "").Replace(" ", "").Trim();

                }


                if (moduleDictionary.ContainsKey("自身风险")&&
                    moduleDictionary["自身风险"] > 0)
                { 
                    //riskInformation.Add(new JProperty("judgement_list", JudgementList));       //裁判文书 
                    HtmlNodeCollection headerTitles =
                        doc.DocumentNode.SelectNodes("//div[contains(@class,\"panel-heading\") and contains(@class,\"risk-hpanel\")]");

                    HtmlNodeCollection panelDatas =
                       doc.DocumentNode.SelectNodes("//section[contains(@class,\"panel\") and  contains(@class,\"m-b-xs\")]");


                    for (int i = 0; i < panelDatas.Count; i++)
                    {
                        string headerTitle = headerTitles[i].InnerText.Replace(" ", "").Trim().Replace("\n", "");

                        string headerKey = commentList[headerTitle];

                        HtmlNode panelData = panelDatas[i];

                        JObject data = null;

                        if (panelData.ParentNode.HasAttributes && panelData.ParentNode.Attributes["Id"] != null
                            && panelData.ParentNode.Attributes["Id"].Value == "judgementList")
                        {
                            data = JudgementList;                   //裁判文书 

                        }
                        else
                        {

                            data = ParseOtherInformation(panelData);  //其它信息 

                        }

                        if (data.Properties().Count() > 0)
                        {
                            data.Add(new JProperty("comment", headerTitle));
                        }

                        riskInformation.Add(new JProperty(headerKey, data));

                    }

                }


                if (riskInformation.Properties().Count() < 1)
                {
                    riskInformation.Add(new JProperty("message", "没有查询到相关的风险信息"));
                }
                else 
                {
                    riskInformation.Add(new JProperty("unique", this.Unique));
                    riskInformation.Add(new JProperty("company_name", this.CompanyName));

                }
                

                return riskInformation; 

            }
            catch (Exception ex)
            {

                MyLog().Error("详情链接解析:" + ex.ToString());
            }

            return new JObject();
           
        }

        public override string ToString()
        {
            JObject riskInformation = ParseRiskInformation();

            return riskInformation.ToString();
        }


    }
}
